// 腾讯坐标逆向解析工具类
const config = require(`../config.js`);

// 腾讯地图逆向解析地址
function showAddress(latitude, longitude, callback){
  let mapApiUrl = `https://apis.map.qq.com/ws/geocoder/v1/?location=${latitude},${longitude}&key=${config.mapSecret}&get_poi=1`;
  wx.request({
    url: mapApiUrl,
    data: {},
    method: `GET`,
    success: (res) => {
      if (res.statusCode == 200 && res.data.status == 0) {
          //转换后匹配的地址
          let newWhere = ''
          if(res.data.result.formatted_addresses) {
            newWhere = (res.data.result.formatted_addresses.recommend).substr(0, 300);
          }
          //pois
          let pois = res.data.result.pois
          // 地址的详细信息
          let addressInfo = {
          // 省信息
          province: res.data.result.ad_info.province,
          // 城市信息
          city: res.data.result.ad_info.city,
          // 区信息
          district: res.data.result.ad_info.district,
        }
          callback(newWhere, pois, addressInfo);
      }
    }
  })
}

/**
 * 判断是否在指定区域
 */
function judgeAddress(
  province = "", 
  provinceRange = [], 
  city = "", 
  cityRange = [], 
  district = "", 
  districtRange = []
  ) {
    // 判断器
    function judgeTool (list, value) {
      let res = list.find(function (val) {
        return value === val
      })
      if (!res) {
        return false;
      }else {
        return true;
      }
    }
  // 处理数据类型
  if (typeof provinceRange === "string") {
    provinceRange = [provinceRange]
  }
  if (typeof cityRange === "string") {
    cityRange = [cityRange]
  }
  if (typeof districtRange === "string") {
    districtRange = [districtRange]
  }
  // 判断省范围
  if (provinceRange.length > 0 && province != "") {
    let res = judgeTool(provinceRange, province)
    if (!res) {
      return false;
    }
  }
  // 判断城市范围
  if (cityRange.length > 0 && city != "") {
    let res = judgeTool(cityRange, city);
    if (!res) {
      return false;
    }
  }
  // 判断区域范围
  if (districtRange.length > 0 && district != "") {
    let res = judgeTool(districtRange, district)
    if (!res) {
      return false;
    }
  }
  return true;
}

module.exports = {
  showAddress: showAddress,
  judgeAddress: judgeAddress
}